﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using MxitAPI;

namespace MxitGUI {
    public partial class ContactsList : UserControl {

        // List view variables
        
        private ColumnHeader columnNickName;
       // private ColumnHeader columnPresence;
       // private ColumnHeader columnMood;
        //private ColumnHeader columnNotifications;

        private Contacts contacts;
        private ChatSessions chatSessions;
        //private List<Contact> contactList;
        private Dictionary<int, ContactItem> contactDict;

        public ContactsList() {
            InitializeComponent();
            InitListView();

            contactDict = new Dictionary<int, ContactItem>();
        }

        private void InitListView() {
            lViewContacts = new ListView();
            columnNickName = new ColumnHeader( "Name" );
            
            //columnPresence = new ColumnHeader( );
            //columnMood = new ColumnHeader();
           // columnNotifications = new ColumnHeader();

            lViewContacts.Dock = DockStyle.Fill;
            lViewContacts.HeaderStyle = ColumnHeaderStyle.None;
            lViewContacts.View = View.Details;
            lViewContacts.FullRowSelect = true;
            lViewContacts.Sorting = SortOrder.Ascending;

            columnNickName.Width = 150;
            //columnPresence.Width = 100;
            //columnMood.Width = 100;
            //columnNotifications.Width = 100;

            lViewContacts.Columns.AddRange( new ColumnHeader[] { columnNickName } ); //, columnPresence } ); //, columnMood } ); //, columnNotifications 

            ImageList imageList = new ImageList();
            imageList.Images.Add( MxitGUI.Resources.offline );//Image.FromFile( "offline.png" ) );
            imageList.Images.Add( MxitGUI.Resources.online );//Image.FromFile( "online.png" ) );
            imageList.Images.Add( MxitGUI.Resources.away ); //Image.FromFile( "away.png" ) );
            imageList.Images.Add( MxitGUI.Resources.dnd );//Image.FromFile( "dnd.png" ) );
            //lViewContacts.LargeImageList.Images.Add( new Bitmap( 10, 10 ) );
            lViewContacts.SmallImageList = imageList;

            this.Controls.Add( lViewContacts );
            this.lViewContacts.ItemActivate += new System.EventHandler(this.lViewContacts_ItemActivate );
            lViewContacts.MouseDown += new MouseEventHandler( HandleMouseDown );

            MenuItem[] menuItems = { 
                                       new MenuItem( "Edit Contact", new EventHandler( HandleEditContact ) ),
                                       new MenuItem( "Delete", new EventHandler( HandleDeleteContact ) ),
                                   };
            lViewContacts.ContextMenu = new ContextMenu( menuItems );

        }

        public void Init( Contacts contacts, ChatSessions chatSessions ) {
            this.chatSessions = chatSessions;
            this.contacts = contacts;

            //contactList = new List<Contacts>();

            contacts.ContactAdded += HandleContactAdded;
            contacts.ContactRemoved += HandleContactRemoved;
            contacts.ContactChanged += HandleContactChanged;
            chatSessions.ChatSessionCreated += HandleChatSessionCreated;

            contacts.NewSubscription += HandleNewSubscription;
        }

        private void HandleDeleteContact( object sender, EventArgs e ) {
            ContactItem contactItem = ( ContactItem ) lViewContacts.SelectedItems[0];
            RemoveContactHandler handler = new RemoveContactHandler( contactItem.Contact.ContactId );
            handler.Execute();
            //HandleContactRemoved(
        }

        private void HandleEditContact( object sender, EventArgs e ) {
            ContactItem contactItem = ( ContactItem ) lViewContacts.SelectedItems[0];
            ( new EditContactWindow( contactItem.Contact ) ).ShowDialog();
        }

        private void HandleMouseDown( object sender, MouseEventArgs e ) {
            if ( e.Button == MouseButtons.Right ) {
                // Get the source control
                Control control = ( Control ) sender;

                if ( control.ContextMenu != null ) {
                    // Show the context menu
                    control.ContextMenu.Show( control, new Point( e.X, e.Y ) );
                }
            }
        }

        public void HandleNewSubscription( Contacts sender, NewSubscriptionEventArgs e) {
            NewSubcriptionWindow newSubscriptionWindow = new NewSubcriptionWindow( e.RawSubscription );
            newSubscriptionWindow.ShowDialog();
            //e.RawSubscription.
        }

        public void UpdateContacts() {
            ( new GetContactsHandler() ).Execute();
        }

        public void HandleContactAdded( Contacts sender, ContactsEventArgs e ) {

            if ( InvokeRequired ) {
                Invoke( new ContactsEventHandler( HandleContactAdded ), sender, e );
                return;
            }

            ContactItem item = new ContactItem( e.Contact );
            contactDict.Add( e.Contact.ContactId, item );
            lViewContacts.Items.Add( item );

        }

        public void HandleContactRemoved( Contacts sender, ContactsEventArgs e ) {

            if ( InvokeRequired ) {
                Invoke( new ContactsEventHandler( HandleContactRemoved ), sender, e );
                return;
            }

            try {
                lViewContacts.Items.Remove( contactDict[e.Contact.ContactId] );
                contactDict.Remove( e.Contact.ContactId );
            }
            catch ( KeyNotFoundException ex ) { } 

        }

        public void HandleContactChanged( Contacts sender, ContactsEventArgs e ) {

            if ( InvokeRequired ) {
                Invoke( new ContactsEventHandler( HandleContactChanged ), sender, e );
                return;
            }
            
            try {

                lViewContacts.Items.Remove( contactDict[e.Contact.ContactId] );
                contactDict.Remove( e.Contact.ContactId );
                ContactItem item = new ContactItem( e.Contact );
                contactDict.Add( e.Contact.ContactId, item );
                lViewContacts.Items.Add( item );
                //contactDict[e.Contact.ContactId] = item;
            }
            catch ( KeyNotFoundException ex ) { } 



        }

        /*
        public void HandleContactsEvent( Contacts contacts, ContactsEventArgs e ) {
             
            if ( InvokeRequired ) {
                Invoke( new ContactsEventHandler( HandleContactsEvent ), contacts, e );
                return;
            }

            List<Contact> contactsList = contacts.GetAllContacts();
            foreach ( Contact contact in contactsList ) {
                //ListViewItem item = new ListViewItem( contact.NickName );
                ContactItem item = new ContactItem( contact );
                //item.NickName = contact.NickName;
                lViewContacts.Items.Add( item );
            }
        }
         */

        public void HandleChatSessionCreated( ChatSessions chatSessions, AffectedChatSessionsEventArgs e ) {

            if ( InvokeRequired ) {
                Invoke( new ChatSessionsEventHandler( HandleChatSessionCreated ), chatSessions, e );
                return;
            }

            // Todo Handle the response on the contacts list when a chat session is opened

        }

        private void lViewContacts_ItemActivate( object sender, EventArgs e ) {
            ListView.SelectedListViewItemCollection selectedContactItems = lViewContacts.SelectedItems;
            foreach ( ListViewItem item in selectedContactItems ) {
                ContactItem contactItem = ( ContactItem ) item;

                chatSessions.TryCreateChatSession( contactItem.Contact );
                //chatSessions.DoNewMessagesReceived();
            }
        }


    }

    class ContactItem : ListViewItem {

       /* public int ContactId { get; set; }
        public string NickName { get; set; }
        public ContactType ContactType { get; set; }
        public Mood Mood { get; set; }
        public Presence Presence { get; set; }
        public string Group { get; set; }
        */
        public Contact Contact { get; set; }

        public ContactItem( Contact contact ) : base() {
            Contact = contact;
            //ListViewItem v = new ListViewItem( new string[] { contact.NickName, contact.Presence.ToString(), contact.Mood.ToString(), "0" } );
            Text = contact.NickName;
            switch( contact.Presence ){
                case Presence.Offline:
                    ImageIndex = 0;
                    break;
                case Presence.Online:
                    ImageIndex = 1;
                    break;
                case Presence.Away:
                    ImageIndex = 2;
                    break;
                case Presence.DoNotDisturb:
                    ImageIndex = 3;
                    break;
            
            }
            //this.ImageList.Images.Add( new Bitmap( 10, 10 ) ); //Image.FromFile( "online.png" )
           // this.image
           // SubItems.Add(  );
            //SubItems.Add(contact.Presence );
            //SubItems.Add( contact.Mood.ToString() );
            //SubItems.Add( I );
           
            
           /* ContactId = Contact.ContactId;
            NickName = Contact.NickName;
            ContactType = contact.ContactType;
            Mood = contact.Mood;
            Presence = contact.Presence;
            Group = contact.Group;
            */
            //Text = NickName;
        }
    }


}
